「...」 後面必定是陣列
const params = [ "hi", 3 ,true ];
const other = [ 1, 2, ...params ]; //[1,2,"hi",3 true]
用在函式呼叫
function sum(a,b,c){
return a + b + c
}
const args =[1,2,3];
sum(...args)
//6
把可迭代(String/Array/TypedArray/Map/Set)或與陣列相似的物件轉成陣列
const aString = "foo"
const char = [...aString]
//[ "f", "o","o" ]
將類陣列轉為陣列
let doms = document.querySelectorAll('li')
let newDoms = [...doms] //變成陣列了
收集剩餘的值,並轉成陣列
位置必定在最後一位
function leftMoney(ming, ...money){
console.log(ming, money)
}
leftMoney('小明', 100, 200, 300) //小明 [100, 200, 300]
function sum(...numbers){
const result = 0
numbers.forEach(function (number)){
result += number
})
return result
}
}
sum(1) //1
sum(1,2,3,4,5) //15
const [x, ...y] = [1, 2, 3]
console.log(x) //1
console.log(y) //[2,3]
const [x, y, ...z] = [1]
console.log(x) //1
console.log(y) //undefined
console.log(z) //[]
其餘參數的值在傳入的時候沒有實際值時,會是空陣列